package com.codi.fcloud.ufx.hssale.query;

import com.codi.base.log.annotation.Loggable;
import com.codi.base.util.ExceptionUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.exception.HundsunAPIException;
import com.codi.fcloud.ufx.HsUtil;
import com.codi.fcloud.ufx.UfxSDKFactory;
import com.codi.fcloud.ufx.constant.HSInputParameterNames;
import com.codi.fcloud.ufx.constant.UrlConstants;
import com.codi.trade.dto.HsTradeConfirmQryDto;
import com.codi.trade.response.HsTradeConfirmQryResponse;
import com.codi.trade.service.TradeConfirmQueryService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service("tradeConfirmQueryService")
public class TradeConfirmQuery extends UfxSDKFactory implements TradeConfirmQueryService {

    // 交易确认查询
    @Loggable
    @Override
    public Map<String, Object> query(Integer requestNum, Integer queryFlag, Integer beginNum, String sortDirection,
                                     String taAcco, String clientId, String beginDate, String endDate, String allotNo, String taConfirmFlag,
                                     String tradeAccount, String fundCode, String businCode, String trafficFlag, String targetFundCode,
                                     String taSerialId, String fundType, String targetFundType, String capitalMode, String scheduledProtocolId) {

        try {

            // 获取第一页
            Map<String, Object> request = getRequestParams(requestNum, queryFlag, beginNum, sortDirection, taAcco,
                clientId, beginDate, endDate, allotNo, taConfirmFlag, tradeAccount, fundCode, businCode,
                trafficFlag, targetFundCode, taSerialId, fundType, targetFundType, capitalMode,
                scheduledProtocolId);

            List<Map<String, Object>> response = getUfxSDK().query(getTarget(), request);

            // 如果requestNum是我们系统定义的最大值，则表明数据需要全部取出来
            getNextResponse(request, response, requestNum);

            return appendLog(request, response);
        } catch (Exception exception) {
            ExceptionUtil.logError(logger, getTarget(), exception);
            throw new HundsunAPIException(ExceptionUtil.getMessage(exception));
        }
    }

    // 交易确认查询
    @Loggable
    @Override
    public Map<String, Object> query(Integer requestNum, Integer queryFlag, Integer beginNum, String sortDirection,
                                     String clientId, String taConfirmFlag, String tradeAccount) {
        return query(requestNum, queryFlag, beginNum, sortDirection, "", clientId, "", "", "", taConfirmFlag,
            tradeAccount, "", "", "", "", "", "", "", "", "");
    }

    @Override
    public List<HsTradeConfirmQryResponse> query(HsTradeConfirmQryDto dto) {

        String trustWay = apiValueMap.get(HSInputParameterNames.TRUST_WAY);

        Map<String, Object> request = new HashMap<String, Object>();
        request.put("net_no", getString(dto.getNet_no(), DEF_NET_NO));//	C9	网点代码	N	不传则使用默认值"0001" ，有传值（包括空）则使用所传值
        request.put("request_num", getString(dto.getRequest_num(), "50"));//	N8	请求行数	Y	最大不能超过50；即最大返回记录条数不会超过50条；
        request.put("reqry_recordsum_flag", getString(dto.getReqry_recordsum_flag(), "0"));//	C1	重新统计总记录数标志	Y	0-不重新统计；1-重新统计；
        request.put("qry_beginrownum", getString(dto.getQry_beginrownum(), "0"));//	N8	查询起始行号	N	比如总记录是100，每50条分页；那么需要查询2次；第1次查询请求行数传50，重新统计总记录数传1，查询起始行号request.put("传1；第2次查询请求行数传50，重新统计总记录数传0，查询起始行号传51；
        request.put("sort_direction", getString(dto.getSort_direction()));//	C1	返回排序方式	N
        request.put("trade_acco", getString(dto.getTrade_acco()));//	C17	交易账号	N	交易账号、客户编号、TA确认编号至少有一个为必填项
        request.put("ta_acco", getString(dto.getTa_acco()));//	C12	TA账号	N
        request.put("client_id", getString(dto.getClient_id()));//	C17	客户编号	N
        request.put("fund_code", getString(dto.getFund_code()));//	C6	基金代码	N
        request.put("fund_busin_code", getString(dto.getFund_busin_code()));//	C3	业务代码	N
        request.put("start_date", getString(dto.getStart_date()));//	C8	开始日期	N
        request.put("end_date", getString(dto.getEnd_date()));//	C8	到期日期	N
        request.put("allot_no", getString(dto.getAllot_no()));//	C24	申请编号	N
        request.put("ta_serial_id", getString(dto.getTa_serial_id()));//	C20	TA确认编号	N
        request.put("busin_board_type", getString(dto.getBusin_board_type()));//	C2	业务大类	N
        request.put("busin_ass_code", getString(dto.getBusin_ass_code()));//	C2	业务辅助代码	N
        request.put("protocol_traffic_flag", getString(dto.getProtocol_traffic_flag()));//	C1	定期定额协议业务标志	N
        request.put("target_fund_code", getString(dto.getTarget_fund_code()));//	C6	目标基金代码	N
        request.put("ofund_type", getString(dto.getOfund_type()));//	C1	基金类型	N
        request.put("target_fund_type", getString(dto.getTarget_fund_code()));//	C1	目标基金类型	N
        request.put("capital_mode", getString(dto.getCapital_mode()));//	C2	资金方式	N
        request.put("trust_way", trustWay);//	C1	交易委托方式	N
        request.put("taconfirm_flag", getString(dto.getTaconfirm_flag()));//	C1	确认标志	N
        request.put("scheduled_protocol_id", getString(dto.getScheduled_protocol_id()));//	C20	定投协议号	N


        try {
            //
            List<Map<String, Object>> response = getUfxSDK().query(getTarget(), request);

            return HsUtil.convertList(appendLog(request, response), HsTradeConfirmQryResponse.class);

        } catch (Exception exception) {
            ExceptionUtil.logError(logger, getTarget(), exception);
            throw new HundsunAPIException(ExceptionUtil.getMessage(exception));
        }
    }

    /**
     * 获取请求参数
     *
     * @param requestNum
     * @param queryFlag
     * @param beginNum
     * @param sortDirection
     * @param taAcco
     * @param clientId
     * @param beginDate
     * @param endDate
     * @param allotNo
     * @param taConfirmFlag
     * @param tradeAccount
     * @param fundCode
     * @param businCode
     * @param trafficFlag
     * @param targetFundCode
     * @param taSerialId
     * @param fundType
     * @param targetFundType
     * @param capitalMode
     * @param scheduledProtocolId
     * @return
     */
    private Map<String, Object> getRequestParams(Integer requestNum, Integer queryFlag, Integer beginNum,
                                                 String sortDirection, String taAcco, String clientId, String beginDate, String endDate, String allotNo,
                                                 String taConfirmFlag, String tradeAccount, String fundCode, String businCode, String trafficFlag,
                                                 String targetFundCode, String taSerialId, String fundType, String targetFundType, String capitalMode,
                                                 String scheduledProtocolId) {
        String trustWay = apiValueMap.get(HSInputParameterNames.TRUST_WAY);

        Map<String, Object> request = new HashMap<String, Object>();
        request.put("trust_way", ""); // 交易委托方式   zx 2018年4月8日15:13:32   因为传2会 查不到柜台的数据 所以 这边不传了
        request.put("request_num", Objects.equals(requestNum, GlobalConstant.MAX_REQUEST_NUM) ? 50: requestNum); // 请求行数
        request.put("reqry_recordsum_flag", queryFlag); // 重新统计总记录数标志
        request.put("qry_beginrownum", beginNum); // 查询起始行号
        request.put("sort_direction", sortDirection); // 返回排序方式
        request.put("ta_acco", taAcco); // TA账号
        request.put("client_id", StringUtil.isEmpty(clientId) ? "" : clientId); // 客户编号
        request.put("allot_no", allotNo); // 申请编号
        request.put("trade_acco", StringUtil.isEmpty(tradeAccount) ? "" : tradeAccount);// 交易帐号
        request.put("fund_code", fundCode); // 基金代码
        request.put("fund_busin_code", businCode); // 业务代码
        request.put("protocol_traffic_flag", trafficFlag);// 定期定额协议业务标志
        request.put("target_fund_code", targetFundCode); // 目标基金代码
        request.put("start_date", beginDate); // 开始日期；
        request.put("end_date", endDate);// 到期日期
        request.put("ta_serial_id", taSerialId);// TA确认编号；
        request.put("fund_type", fundType); // 基金类型；
        request.put("target_fund_type", targetFundType);// 目标基金类型
        request.put("capital_mode", capitalMode);// 资金方式
        request.put("taconfirm_flag", taConfirmFlag); // 确认标志
        request.put("scheduled_protocol_id", scheduledProtocolId);// 定投协议号

        return request;
    }

    @Override
    protected String getTarget() {
        return UrlConstants.PREFIX_SALE + UrlConstants.TRADE_CONFIRM_QRY;
    }

}
